﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using FarseerGames.FarseerPhysics.Mathematics;
using FreeGoo.GameEngine.Renderables;

namespace FreeGoo.WpfRenderer
{
    public abstract class RendererWithCanvas : Renderer
    {
        public RendererWithCanvas(RendererFactory factory, Renderable renderable)
            : base(factory, renderable)
        {
        }

        public Canvas Canvas { get; set; }
        protected RotateTransform RotateTransform { get; set; }
        protected TranslateTransform TranslateTransform { get; set; }
        public void SetCanvasContent(FrameworkElement frameworkElement)
        {
            Delete();
            Canvas = new Canvas();
            Canvas.Children.Add(frameworkElement);
            TransformGroup transformGroup = new TransformGroup();
            RotateTransform = new RotateTransform();
            TranslateTransform = new TranslateTransform();
            transformGroup.Children.Add(RotateTransform);
            transformGroup.Children.Add(TranslateTransform);
            Canvas.RenderTransform = transformGroup;
            Factory.Canvas.Children.Add(Canvas);
        }

        public virtual Vector2 GetPosition()
        {
            return Renderable.Position;
        }

        public override void Update()
        {
            Vector2 pos = GetPosition();
            TranslateTransform.X = pos.X;
            TranslateTransform.Y = pos.Y;
            RotateTransform.Angle = (Renderable.Rotation * 360) / (2 * Math.PI);
        }

        public override void Delete()
        {
            if (Canvas != null)
            {
                Factory.Canvas.Children.Remove(Canvas);
                Canvas = null;
            }
        }
    }
}
